/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 *
 * 			http://www.kkkd.com/
 *
 * ========================================================
 */
package com.simon.mengkou.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Follow;
import com.simon.mengkou.data.bean.base.User;
import com.simon.mengkou.data.bean.req.FollowReq;
import com.simon.mengkou.data.bean.req.ShareOrderLikeReq;
import com.simon.mengkou.data.cache.DataCacheImpl;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.ui.adapter.UserVideoAdapter;
import com.simon.mengkou.ui.base.BaseSocialShareFullFragment;
import com.simon.mengkou.ui.dialog.ShareDialog;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/3/3.
 * desc    : 首页关注界面
 */
public class UserVideoFragment extends BaseSocialShareFullFragment
        implements PullToRefreshBase.OnRefreshListener2<ListView>{
    @Bind(R.id.common_pulltorefresh_id_list)
    PullToRefreshListView mPtrView;

    private UserVideoAdapter mAdapter;
    private int mPage = 0;
    private Follow mShareFollow;
    private String mUserId;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mUserId = getArguments().getString(CstOuer.KEY.USER_ID);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.layout_common_message_pulltorefresh_list);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this, getView());

        mPtrView.setOnRefreshListener(this);
        mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
        mPtrView.setTag(false);

        mAdapter = new UserVideoAdapter(mActivity, this);
        mPtrView.setAdapter(mAdapter);

        //获取缓存
        List<Follow> datas = null;
        if(OuerApplication.mUser.getUserId().equals(mUserId)) {
           datas = OuerApplication.mCacheFactory.getCache(DataCacheImpl.UserVideoCache.class,
                    OuerApplication.mUser.getUserId())
                    .getData();
        }

        if(UtilList.isNotEmpty(datas)) {
            mAdapter.setList(datas);
            mPtrView.setTag(true);
            mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            mPtrView.setTag(false);
            //首次失败重试
            setOnRetryListener(new OnRetryListener() {
                @Override
                public void onRetry() {
                    getData(0, EDirection.REFRESH);
                }
            });
        }

        getData(0, EDirection.REFRESH);


        registerAction(CstOuer.BROADCAST_ACTION.FOLLOW_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.VIDEO_FOLLOW_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.SHARE_ORDER_LIKE_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.SHARE_ORDER_COMMENT_ACTION);
    }


    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);

        if(CstOuer.BROADCAST_ACTION.FOLLOW_ACTION.equals(intent.getAction())) {
            //更新关注状态
            FollowReq req = (FollowReq) intent.getSerializableExtra(CstOuer.KEY.FOLLOW);
            List<Follow> datas = mAdapter.getData();
            if(UtilList.isNotEmpty(datas)) {
                for(Follow follow : datas) {
                    User user = follow.getUser();
                    if(user.getUserId().equals(req.getTargetId())) {
                        user.setInterested(req.isChecked());
                    }
                }
            }

            mAdapter.notifyDataSetChanged();
        } else if(CstOuer.BROADCAST_ACTION.VIDEO_FOLLOW_ACTION.equals(intent.getAction())) {
            getData(0, EDirection.REFRESH);

            String id =  intent.getStringExtra(CstOuer.KEY.ID);
            List<Follow> datas = mAdapter.getData();

            if(UtilList.isNotEmpty(datas)) {
                for(Follow follow : datas) {
                    if(follow.getId().equals(id)) {
                        follow.setCollected(true);
                    }
                }
            }

        }else if(CstOuer.BROADCAST_ACTION.SHARE_ORDER_LIKE_ACTION.equals(intent.getAction())) {
            ShareOrderLikeReq req = (ShareOrderLikeReq) intent.getSerializableExtra(CstOuer.KEY.LIKE);
            List<Follow> datas = mAdapter.getData();
            boolean flag = false;
            if(UtilList.isNotEmpty(datas)) {
                for(Follow follow : datas) {
                    if(follow.getId().equals(req.getId())) {
                        follow.setLiked(req.isCheck());
                        if(req.isCheck()) {
                            follow.setFaverNum(follow.getFaverNum() + 1);
                        } else {
                            follow.setFaverNum(follow.getFaverNum() - 1);
                        }
                        flag = true;
                    }
                }
            }

            if(flag) {
                mAdapter.notifyDataSetChanged();
            }
        }
        else if(CstOuer.BROADCAST_ACTION.SHARE_ORDER_COMMENT_ACTION.equals(intent.getAction())) {
            String id =  intent.getStringExtra(CstOuer.KEY.ID);
            List<Follow> datas = mAdapter.getData();

            if(UtilList.isNotEmpty(datas)) {
                for(Follow follow : datas) {
                    if(follow.getId().equals(id)) {
                        follow.setCommentNum(follow.getCommentNum() + 1);

                    }
                }
            }

        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        //下拉刷新
        getData(0, EDirection.REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //上拉加载更多
        getData(mPage + 1, EDirection.LOADMORE);
    }

    /**
     * 获取通知消息
     * @param direction
     */
    private void getData(int page, final int direction) {
        AgnettyFuture future = OuerApplication.mOuerFuture.userVideo(page,
                CstOuer.PAGE.DEFAULT_SIZE, mUserId,
                new OuerFutureListener(mActivity){

                    public void onStart(AgnettyResult result) {
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setLoading(true);
                        }
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            mPtrView.setTag(true);
                            setLoading(false);
                        } else {
                            mPtrView.onRefreshComplete();
                        }

                        List<Follow> datas = (List<Follow>) result.getAttach();

                        if(direction == EDirection.REFRESH) {
                            if(OuerApplication.mUser.getUserId().equals(mUserId)) {
                                OuerApplication.mCacheFactory.getCache(DataCacheImpl.UserVideoCache.class,
                                        OuerApplication.mUser.getUserId())
                                        .save(datas);
                            }

                            mPage = 0;
                            if(UtilList.isEmpty(datas)) {
                                mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
                                setEmptyText(R.string.user_collection_video_empty);
                                mAdapter.clearAll();
                            } else {
                                if(UtilList.getCount(datas) < CstOuer.PAGE.DEFAULT_SIZE) {
                                    mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                                } else {
                                    mPtrView.setMode(PullToRefreshBase.Mode.BOTH);
                                }

                                mAdapter.setList(datas);
                            }
                        } else {
                            if(UtilList.getCount(datas) < CstOuer.PAGE.DEFAULT_SIZE) {
                                mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }

                            mPage++;
                            mAdapter.addList(datas);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }
                });

        attachDestroyFutures(future);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.share_id_qq://分享到qq
                shareOrder(SHARE_MEDIA.QQ, mShareFollow);
                break;
            case R.id.share_id_wechat://分享到微信
                shareOrder(SHARE_MEDIA.WEIXIN, mShareFollow);
                break;
            case R.id.share_id_sina://分享到新浪
                shareOrder(SHARE_MEDIA.SINA, mShareFollow);
                break;
            case R.id.share_id_qzone://分享qq空间
                shareOrder(SHARE_MEDIA.QZONE, mShareFollow);
                break;
            case R.id.share_id_circle://分享微信朋友圈
                shareOrder(SHARE_MEDIA.WEIXIN_CIRCLE, mShareFollow);
                break;
        }
    }

    /**
     * 分享
     * @param platform
     */
    private void shareOrder(SHARE_MEDIA platform, Follow follow) {
        if(UtilList.isNotEmpty(follow.getImageArray())) {
            share(platform, getString(R.string.app_name),
                    follow.getContent(), follow.getShareUrl(), follow.getImageArray().get(0).getUrl());
        } else {
            share(platform, getString(R.string.app_name),
                    follow.getContent(), follow.getShareUrl(), follow.getVideoCover());
        }
    }

    /**
     * 显示分享对话框
     * @param follow
     */
    public void showShareDialog(Follow follow) {
        mShareFollow = follow;
        ShareDialog dialog = new ShareDialog(mActivity, this);
        dialog.showAtLocation(mPtrView, Gravity.CENTER, 0, 0);
    }
}
